#!/usr/bin/env bash
# find-deepdive-app -- Recognizes which DeepDive application current working directory belongs to
#
# Uses $DEEPDIVE_APP environment if available.
##
set -eu

# locate application root
at_deepdive_app_root() {
    # recognize an app directory as defined in ../doc/deepdiveapp.md
    [[ ( -e app.ddlog || -e deepdive.conf ) ]]
}

if [[ -d "${DEEPDIVE_APP:-}" ]]; then
    cd "$DEEPDIVE_APP"
    if at_deepdive_app_root; then
        echo "$DEEPDIVE_APP"
    else
        error "$DEEPDIVE_APP: \$DEEPDIVE_APP does not point to a DeepDive application: either app.ddlog or deepdive.conf should be present"
    fi
else
    PWD_orig=$PWD
    while ! at_deepdive_app_root && [[ $PWD != / ]]; do
        cd ..
    done

    if at_deepdive_app_root; then
        pwd
    else
        error "$PWD_orig: Not inside a DeepDive application: either app.ddlog or deepdive.conf should be present in a parent directory"
    fi
fi
